function addChild(btn) {
	var form = $($(btn).parents(".form").parent().children(".form")[0]);
	var id = getField(form, "id");
	var uuid = getField(form, "uuid");
	createFrame();
 	setData($("#category-adder"), { parentId: id, parentUuid: uuid });
}
function addBrother(btn) {
	var form = $($(btn).parents(".form").parent().children(".form")[0]);
	var parentId = getField(form, "parentId");
	var parentUuid = getField(form, "parentUuid");
	createFrame();
 	setData($("#category-adder"), { parentId: parentId, parentUuid: parentUuid });
}
function callback(form, result, data) {
	var treeView = $("#dataTable");
	var item = treeView.find("li[id=" + data.parentId + "]")[0];
	result.data.label = result.data.name;
	if (!item) {
		treeView.jqxTree("addTo", result.data);
	} else {
		item = treeView.jqxTree("getItem", item);
		treeView.jqxTree("addTo", result.data, item);
	}
}
function deleteCallback(form, result, data) {
	var treeView = $("#dataTable");
	var item = treeView.find("li[id=" + data.id + "]")[0];
	treeView.jqxTree("removeItem", item);
	clearData(form);
	$("#category-editer>.form").hide();
}
function doSubmit(form, data, url) {
	var attrs = form.find(".attribute-box");
	delete data.key;
	delete data.value;
	var val = {};
	for (var i = 0; i < attrs.length; i++) {
		var attr = $(attrs[i]);
		var key = attr.find("input[name=key]");
		var value = attr.find("input[name=value]");
		if(!key.val()){
			tipErr(key, "属性名是必须的。");
			return false;
		}
		if(!value.val()){
			tipErr(value.parent(), "属性值是必须的。");
			return false;
		}
		val[key.val()] = value.val();
	}
	data.attributes = JSON.stringify(val);

	var fullName = data.name;
	var levelType = 1;
	var item = $(".jqx-tree-item-li[id][aria-selected=true]:first");
	while ((item = item.parents(".jqx-tree-item-li[id]:first")).length) {
		fullName = item.find("div.jqx-tree-item:first").text() + "\\" + fullName;
		++levelType;
	}
	data.full_name = fullName;
	data.level_type = levelType;
}
function createFrame() {
 	_editerIndex = layer.open({
		id: "categoryEditer",
		title: "增加地址信息",
	    type: 1,
	    skin: "layui-layer-rim",
	    area: ["780px", "600px"],
	    content: 
	    '<div id="category-adder" class="form" style="height: 100%;overflow: auto;">' +
	    '<input type="hidden" name="submit-url" value="category/add.do" />' +
		'<input type="hidden" name="parentId" />' +
		'<input type="hidden" name="parentUuid" />' +
		'<label class="from-label" for="name">名称：</label> ' +
		'<input type="text" name="name" allowBlank="false" class="form-control" placeholder="名称" style="width:600px;"/>' +
		'<br>'+
		'<div class="input-box" style="width: 600px;text-align: center;">'+
		'<label class="from-label" ></label>' +
		'<label class="from-label" ></label>' +
		/**'<input type="button" id="add-new-attr" class="btn btn-sm btn-primary" style="margin: 0;" value="添加新属性">' +*/
		'</div>'+
		'</div>'+
		'<div class="form" style="position: absolute;bottom: 0px;width: 100%;text-align: right;background-color: #DDD;">' +
		'<input type="button" class="btn btn-sm btn-success" onclick="submitEditer(this, true, callback)" value="保存"/>' +
		'<input type="button" class="btn btn-sm btn-info" onclick="closeEditer(this)" value="返回"/>' +
		'</div>',
	});
 	//$("#category-adder #add-new-attr").click();
 	$("#category-adder").click();
}
$(function(){
	var treeView = $("#dataTable");
	$.ajax({
		async: false,
		url: "category/tree.do",
		success: function(data, status) {
        	map(data.data, "name", "label");
        	for(var i = 0; i < data.data.length; i++){
        		data.data[i].items = [{ label: "Loading..." }];
        	}
			treeView.jqxTree({source: data.data, width: "23%", height: 650});
			treeView.on("expand", function(event){
				var label = treeView.jqxTree("getItem", event.args.element).label;
				var element = $(event.args.element);
				var loader = false;
	            var loaderItem = null;
	            var children = element.find("ul:first").children();
	            children.each(function(index, item){
	            	item = treeView.jqxTree("getItem", item);
	            	if(item && item.label == "Loading..."){
	            		loaderItem = item;
	            		loader = true;
	            		return false;
	            	}
	            });
                if (loader) {
                    $.ajax({
                		url: "category/tree.do",
                		data: {id : loaderItem.parentId },
                        success: function (data, status) {
                        	map(data.data, "name", "label");
                        	for(var i = 0; i < data.data.length; i++){
                        		data.data[i].items = [{ label: "Loading..." }];
                        	}
                        	treeView.jqxTree("addTo", data.data, element[0]);
                        	children.each(function(index, item) {
                            	treeView.jqxTree("removeItem", item);
                        	});
                        }
                    });
                }
			});
			treeView.on("select", function(event){
				$.ajax({
					url: "category/get.do",
					data: { id: event.args.owner.selectedItem.id },
					success: function(data, status){
						$("#category-editer .form").show();
						if(data && data.data){
							$("input[name='id']").val(data.data.id);
							setData($("#category-editer"), data.data);
							var attrs = data.data.attributes;
							try {
								attrs = eval("(" + attrs + ")");
							} catch (e) {
								attrs = [];
							}
							$(".attribute-box").remove();
							for(var item in attrs){
								//$("#add-new-attr").click();
								var attrBox = $(".attribute-box:last");
								$(attrBox).find("input[name=key]").val(item);
								$(attrBox).find("#tags-input").tagsinput("add", attrs[item]);
							}
							if($(".attribute-box").length == 0){
								//$("#add-new-attr").click();
							}
						}
					}
				});
			});
		}
	});
	$("#add-new-attr").live("click", function(){
		var parentBox = $(this).parent();
		parentBox.before('<div class="input-box attribute-box" style="display:block;"><label class="from-label" for="key">属性：<notnull></label> <input type="text" class="form-control" allowBlank="false" style="width: 113px" name="key" placeholder="属性名"> <div name="value" allowBlank="false" placeholder="属性值"  class="form-control tags-input" style="width: 480px;"><input id="new-tags-input" type="text" data-role="tagsinput" name="value" placeholder="属性值(可有多个值)      " /></div><input id="tabg-input-delete" type="button" value="×" class="btn-delete"></div>');
		parentBox = parentBox.parent();
		var newTagsInput = parentBox.find("#new-tags-input");
		newTagsInput.tagsinput();
		newTagsInput.attr("id", "tags-input");
		focus(parentBox.find(this));
		if(parentBox.find(".btn-delete").length != 1){
			parentBox.find(".btn-delete").show();
		}
	});
	$(".btn-delete").live("click", function(){
		var parentBox = $(this).parent().parent();
		$(this).parent().remove();
		if(parentBox.find(".btn-delete").length == 1){
			parentBox.find(".btn-delete").hide();
		}
	});
	$("#category-editer>.form").hide();
	//$("#add-new-attr").click();
	$("#name").keypress(function(e) {
		return e.charCode != 92;
	});
});